<template>
  <div class="enquiryApplication">
    <div class="container">
      <!--  地图加载  -->
      <div id="map"></div>
      <infoBox ref="infoBoxRef" id="infoBoxID" v-if="infoVisible"></infoBox>

      <!--  地址搜索  -->
      <div id="myPageTop">
        <input
          id="tipinput"
          @focus="clearDetele = true"
          @keydown.enter="mapSelect"
          :placeholder="$t('enquiry.dimension')"
        />
        <img
          v-if="clearDetele"
          src="@/assets/images/deleteBtn.png"
          class="deleteClearBle"
          @click="clearableHandle"
          alt=""
        />
        <el-button :icon="Search" @click="mapSelect">{{
          $t("enquiry.search")
        }}</el-button>
      </div>

      <!--  图层控件  -->
      <div
        class="airspaceLayer"
        :class="{ layerVisible }"
        @click="airspaceControl"
      ></div>

      <!--  图层控制  -->
      <div v-if="layerVisible" class="layerControl">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
          >{{ $t("enquiry.airspace") }}</el-checkbox
        >
        <el-checkbox-group
          v-model="checkedCities"
          @change="handleCheckedCitiesChange"
        >
          <el-checkbox
            v-for="(airspace, index) in airspaceList"
            :key="airspace.airTypeId"
            :label="airspace.airTypeId"
          >
            <div
              class="checkTitleClass"
              :id="'ckeckName' + index"
              @mouseover="checkMouse(airspace.airTypeName, index)"
            >
              {{ airspace.airTypeName }}
            </div>
          </el-checkbox>
        </el-checkbox-group>
        <el-checkbox
          v-model="measure"
          :label="$t('enquiry.distance')"
          @change="measuringDistance"
          size="large"
        />
        <el-checkbox
          v-model="satellite"
          :label="$t('enquiry.mapStyle')"
          @change="swicthSatellite"
          size="large"
        />
        <el-checkbox
          v-model="grid"
          :label="$t('enquiry.grid')"
          @change="handleGrid"
          size="large"
        />
      </div>
    </div>
  </div>
</template>

<script setup name="enquiry">
import { onMounted, ref, reactive } from "vue";
import { Search } from "@element-plus/icons-vue";
import { getAirTypeIds, download } from "@/api/airSpace/enquiry";
import { getAirspaceType } from "@/api/airSpace/airSpaceSetUp";
import infoBox from "./infoBox.vue";
const infoBoxRef = ref("");
let airMap = ref(null);
let auto = ref(null);
let placeSearch = ref(null);
let position = ref(null);
var ruler = ref(null);
let longitude = ref("");
let latitude = ref("");
const layerVisible = ref(false);
let dataPoi = reactive({});
let measure = ref("");
let satellite = ref("");
let grid = ref("");
const airspaceList = ref([]);
const checkAll = ref(false);
const checkedCount = ref("");
const checkedCities = ref([]);
const isIndeterminate = ref(true);
const infoVisible = ref(false);
const airList = ref([]);
const clearDetele = ref(false);
import { ElMessage } from "element-plus";
import { getCurrentInstance } from "vue";
const { $t } = getCurrentInstance().proxy;
// 地图初始化
const initMap = () => {
  airMap = new AMap.Map("map", {
    pitchEnable: false,
    zoom: 14,
    pitch: 35,
    rotation: 45,
    resizeEnable: true,
    viewMode: "3D",
    zooms: [2, 20],
    center: [120.14819, 30.245953],
    mapStyle: "amap://styles/fresh",
  });

  // 获取地图上点击的经纬度
  airMap.on("click", function (e) {
    longitude = e.lnglat.lng;
    latitude = e.lnglat.lat;
    console.log(longitude, latitude);
  });

  //输入提示
  const autoOptions = {
    input: "tipinput",
  };

  AMap.plugin(["AMap.PlaceSearch", "AMap.AutoComplete"], function () {
    auto = new AMap.AutoComplete(autoOptions);
    // placeSearch = new AMap.PlaceSearch({autoOptions}); //构造地点查询类
    placeSearch = new AMap.PlaceSearch({
      map: airMap,
    }); //构造地点查询类
    auto.on("select", select); //注册监听，当选中某条记录时会触发
    function select(e) {
      dataPoi = e.poi;
    }
  });
};

function clearableHandle() {
  document.getElementById("tipinput").value = "";
  clearDetele.value = false;
}

/**
 * @设置高德地图地理编码城市为杭州
 * */
let geocoder = new AMap.Geocoder({
  // city: "330100", //城市设为杭州，默认：“全国”
});

function onfocusFun() {
  console.log("1111");
}

var marker = new AMap.Marker();
const mapSelect = () => {
  let inputValue = document.getElementById("tipinput");
  if (!inputValue.value) {
    ElMessage.warning($t("enquiry.dimension")); // 请输入地址！
    var mybounds = new AMap.Bounds(
      [120.04403, 30.080745],
      [120.371217, 30.345388]
    );
    airMap.setBounds(mybounds);
    // airMap.clearMap();
    airMap.remove(marker);
  } else {
    geocoder.getLocation(inputValue.value, function (status, result) {
      if (status === "complete" && result.geocodes.length) {
        var lnglat = result.geocodes[0].location;
        console.log(lnglat);
        // document.getElementById('lnglat').value = lnglat;
        marker.setPosition(lnglat);
        airMap.add(marker);
        // airMap.setFitView(marker);
      } else {
        log.error("根据地址查询位置失败");
      }
    });
    // placeSearch.setCity(dataPoi.adcode);
    // placeSearch.search(dataPoi.name); //关键字查询查询
  }
};
const airspaceControl = () => {
  layerVisible.value = !layerVisible.value;
};

//移入事件
function showInFoOver(val, event) {
  infoVisible.value = true;
  let box = document.getElementById("infoBoxID");
  box.style.top = event.pixel.y + "px";
  box.style.left = event.pixel.x + "px";
  infoBoxRef.value.getValue(val);
}

// 全部空域点击
function handleCheckAllChange(val) {
  checkedCities.value = val
    ? airspaceList.value.map((item) => item.airTypeId)
    : [];
  isIndeterminate.value = false;
  if (val) {
    getAirspaceTypeList();
  } else {
    airMap.clearMap();
  }
}

// 单个空域点击
function handleCheckedCitiesChange(value) {
  airMap.clearMap();
  getAirAirspace(value);
  checkedCount.value = value.length;
  checkAll.value = checkedCount.value === airspaceList.value.length;
  isIndeterminate.value =
    checkedCount.value > 0 && checkedCount.value < airspaceList.value.length;
  if (!circle) {
    airMap.remove(circle);
  } else if (!mouseTool) {
    airMap.remove(mouseTool);
  }
}

function checkMouse(val, index) {
  document.getElementById("ckeckName" + index).title = val;
}

// 获取区域列表信息
function getAirspaceTypeList() {
  getAirspaceType().then((response) => {
    if (response.code === 200) {
      airspaceList.value = response.data;
      checkedCities.value = airspaceList.value.map((item) => item.airTypeId);
      checkedCount.value = airspaceList.value.length;
      checkAll.value = true;
      isIndeterminate.value = false;
      getAirAirspace(checkedCities.value);
    }
  });
}

// 请求空域信息
function getAirAirspace(val) {
  val.map((item) => {
    getAirTypeIds(item).then((response) => {
      if (response.code === 200) {
        airList.value = response.data;
        if (airList.value.length > 0) {
          airList.value.map((item) => {
            if (item.circle == 1) {
              // 圆形
              circleDraw(item);
            } else {
              // 多边形
              polygonDraw(item);
            }
          });
        }
      }
    });
  });
}

var circle = null;
function circleDraw(val) {
  circle = new AMap.Circle({
    center: val.pointLocation.split(","),
    radius: val.radius, //半径
    borderWeight: 3,
    strokeColor: val.lineColor,
    strokeOpacity: 1,
    strokeWeight: 6,
    fillOpacity: 0.4,
    strokeStyle: "dashed",
    strokeDasharray: [10, 10],
    // 线样式还支持 'dashed'
    fillColor: val.fullColor,
    zIndex: 50,
  });
  airMap.add(circle);
  // // 缩放地图到合适的视野级别
  // airMap.setFitView([circle]);

  circle.on("mouseover", (event) => {
    showInFoOver(val, event);
  });
}

var mouseTool = null;
function polygonDraw(val) {
  mouseTool = new AMap.Polygon({
    path: eval("[" + val.pointLocation + "]"),
    strokeColor: val.lineColor,
    strokeWeight: 6,
    strokeOpacity: 1,
    fillOpacity: 0.4,
    fillColor: val.fullColor,
    strokeStyle: "solid",
    bubble: true,
  });
  airMap.add([mouseTool]);
  // airMap.setFitView();

  mouseTool.on("mouseover", (event) => {
    showInFoOver(val, event);
  });
}

// 测距
const measuringDistance = (val) => {
  if (val) {
    //自定义样式
    var startMarkerOptions = {
      icon: new AMap.Icon({
        size: new AMap.Size(19, 31), //图标大小
        imageSize: new AMap.Size(19, 31),
        image: "//webapi.amap.com/theme/v1.3/markers/b/start.png",
      }),
      offset: new AMap.Pixel(-9, -31),
    };
    var endMarkerOptions = {
      icon: new AMap.Icon({
        size: new AMap.Size(19, 31), //图标大小
        imageSize: new AMap.Size(19, 31),
        image: "//webapi.amap.com/theme/v1.3/markers/b/end.png",
      }),
      offset: new AMap.Pixel(-9, -31),
    };
    var midMarkerOptions = {
      icon: new AMap.Icon({
        size: new AMap.Size(19, 31), //图标大小
        imageSize: new AMap.Size(19, 31),
        image: "//webapi.amap.com/theme/v1.3/markers/b/mid.png",
      }),
      offset: new AMap.Pixel(-9, -31),
    };
    var lineOptions = {
      strokeStyle: "solid",
      strokeColor: "#368dff",
      strokeOpacity: 1,
      strokeWeight: 2,
    };
    var rulerOptions = {
      startMarkerOptions: startMarkerOptions,
      midMarkerOptions: midMarkerOptions,
      endMarkerOptions: endMarkerOptions,
      lineOptions: lineOptions,
    };
    ruler = new AMap.RangingTool(airMap, rulerOptions);
    ruler.turnOn();
  } else {
    ruler.turnOff();
  }
};

// 构造官方卫星、路网图层
var satelliteLayer = new AMap.TileLayer.Satellite();
var roadNetLayer = new AMap.TileLayer.RoadNet();
//卫星地图
const swicthSatellite = (val) => {
  if (val) {
    airMap.add(satelliteLayer);
  } else {
    airMap.remove(satelliteLayer);
  }
};
//网格
const handleGrid = (val) => {
  if (val) {
    airMap.add(roadNetLayer);
  } else {
    airMap.remove(roadNetLayer);
  }
};

onMounted(() => {
  initMap();
  getAirspaceTypeList();
});
</script>

<style scoped lang="scss">
//隐藏地图logo
:deep(.amap-logo) {
  opacity: 0;
  display: none !important;
  visibility: hidden !important;
}
:deep(.amap-copyright) {
  opacity: 0;
  display: none !important;
  visibility: hidden !important;
}

.enquiryApplication {
  width: 100%;
  height: 100%;
  .container {
    position: relative;
    width: calc(100% - 40px);
    height: 92%;
    margin: 0 20px 20px;
    border-radius: 10px;
    background: white;
    overflow: hidden;

    #map {
      width: 100%;
      height: 100%;
      position: absolute;
    }

    #myPageTop {
      width: 370px;
      height: 40px;
      top: 30px;
      right: 21px;
      position: absolute;
      display: flex;

      .deleteClearBle {
        width: 11px;
        height: 11px;
        position: relative;
        top: 15px;
        right: 40px;
        cursor: pointer;
      }

      input {
        width: 270px;
        height: 40px;
        opacity: 1;
        margin-right: 20px;
        padding: 0 10px;
        border-radius: 4px;
        background: rgba(255, 255, 255, 1);
        border: 1px solid rgba(220, 223, 230, 1);
      }

      .el-button {
        width: 80px;
        height: 40px;
        opacity: 1;
        border-radius: 4px;
        background: rgba(43, 193, 123, 1);
        color: #ffffff;
      }
    }

    .airspaceLayer {
      position: absolute;
      width: 45px;
      height: 45px;
      background: url("@/assets/images/airspacePop.png");
      background-size: 100% 100%;
      right: 20px;
      bottom: 16px;
    }

    .layerVisible {
      background: url("@/assets/images/airspacePop2.png");
      background-size: 100% 100%;
    }

    .layerControl {
      width: 210px;
      height: auto;
      position: absolute;
      z-index: 1000;
      bottom: 76px;
      right: 20px;
      background-color: #ffffff;
      border-radius: 6px;
      box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.2);
      padding: 18px 21px 15px;

      .el-checkbox-group {
        max-height: 250px;
        margin-left: 20px;
        overflow: hidden;
        overflow-y: scroll; /* 显示垂直滚动条 */
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* Internet Explorer and Edge */
        .checkTitleClass {
          width: 150px;
          white-space: nowrap; /* 防止文本换行 */
          overflow: hidden; /* 超出部分隐藏 */
          text-overflow: ellipsis; /* 使用省略号隐藏 */
        }
      }

      .el-checkbox-group::-webkit-scrollbar {
        display: none; /* Safari and Chrome */
      }

      .el-checkbox {
        height: 24px;
      }
    }
  }
}
</style>
<style>
.amap-sug-result {
  position: absolute;
  top: 2%;
  left: 0;
}
</style>
